package com.quxiang.pay.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * HttpClient发送请求
 * 
 * @author liulu
 */
public class HttpClientUtils {
	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

	/**
	 * 创建 http是请求
	 * 
	 * @return
	 */
	private static CloseableHttpClient createSSLClientDefault() {

		SSLContext sslContext;
		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(2000)
				.setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();
		try {
			sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] xcs, String string) {
					return true;
				}
			}).build();

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

			return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig)
					.build();
		} catch (KeyStoreException ex) {
			logger.error("KeyStoreException", ex);
		} catch (NoSuchAlgorithmException ex) {
			logger.error("NoSuchAlgorithmException", ex);
		} catch (KeyManagementException ex) {
			logger.error("KeyManagementException", ex);
		}

		return HttpClients.createDefault();
	}

	public static String httpGet(String url) {

		logger.info("http get 请求 url = {}", url);
		CloseableHttpClient httpClient = createSSLClientDefault();
		CloseableHttpResponse response = null;
		HttpGet get = new HttpGet(url);
		get.setHeader("Accept", "application/xml");
		String result = "";
		try {
			response = httpClient.execute(get);
			int httpCode = response.getStatusLine().getStatusCode();
			if (httpCode == 200) {
				HttpEntity entity = response.getEntity();
				if (null != entity) {
					result = EntityUtils.toString(entity, "UTF-8");
					logger.info("http get 请求 result = {}", result);
				} else {
					logger.info("http get 请求 result is null  = {}", result);
				}
			} else {
				logger.info("http get 请求 error  getStatusCode = {}", httpCode);
			}
		} catch (IOException ex) {
			logger.error("http get 请求 error ", ex);
		} finally {
			if (get != null) {
				get.releaseConnection();
			}

			if (null != response) {
				try {
					response.close();

				} catch (IOException ex) {
					logger.info("http get response close  error  ex = {}", ex);
				}
			}

			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					logger.info("http get httpClient close  error  ex = {}", e);
				}
			}
		}

		return result;

	}

	/**
	 * post xml 請求
	 * 
	 * @return
	 */
	public static String postXml(String url, String param) {

		logger.info("http post xml  请求 url = {}", url);
		CloseableHttpClient httpClient = createSSLClientDefault();
		CloseableHttpResponse response = null;
		HttpPost post = new HttpPost(url);
		post.setHeader("Accept", "application/xml");
		post.setHeader("Content-Type", "application/xml;charset=utf-8");
		String result = "";
		StringEntity entity = null;
		try {

			logger.info("http post xml  请求 param = {}", param);
			if (param == null) {
				return "";
			}
			entity = new StringEntity(param,"utf-8");
			post.setEntity(entity);
			response = httpClient.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity);
					logger.info("http post xml  result ={}", result);
				} else {
					logger.info("http post xml  error resEntity is null");
				}
			} else {
				logger.info("http post xml  error statusCode  e = {}", statusCode);
			}
		} catch (JsonProcessingException e) {
			logger.error("http post xml   JsonProcessingException  e = {}", e);
		} catch (UnsupportedEncodingException e) {
			logger.error("http post xml UnsupportedEncodingException e = {}", e);
		} catch (ClientProtocolException e) {
			logger.error("http post xml ClientProtocolException e = {}", e);
		} catch (IOException e) {
			logger.error("http post xml IOException e = {}", e);
		} finally {
			if (post != null) {
				post.releaseConnection();
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error("http post xml response close e = {}", e);
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					logger.error("http post xml httpClient close e = {}", e);
				}
			}
		}

		return result;
	}

	public static String postJson() {

		return null;
	}

}
